import { jiweiAxios } from "../axios.js";
import { URL, DICT, STATUS } from "../config.js";
import { loginUtil, inputUtils, commonUtil } from "../../../utils/index.js";
import { checkExistParams } from "./params.js";
import iconv from "iconv-lite";
import cheerio from "cheerio";
import { chineseMedicineAdapter } from "../adapter/common/chineseMedicine.js";
import dayjs from "dayjs";

const { CHINESE_MEDICINE_DICT, CHINESE_MEDICINE_DICT_INVERT } =
  commonUtil.getInvertDict(DICT, "CHINESE_MEDICINE_DICT");
const { setPersonStatusAndNote } = commonUtil;

const main = async () => {
  const excelName = await commonUtil.selectExcel();
  const personList = commonUtil.excelToJson(
    excelName,
    CHINESE_MEDICINE_DICT_INVERT
  );
  await inputUtils.input({
    dataList: personList,
    fn: input,
    loginFn: loginUtil.panyuJiweiLogin,
    DICT: CHINESE_MEDICINE_DICT,
    excelName,
  });
};

async function input(person) {
  const originPerson = { ...person };
  person = chineseMedicineAdapter(person);

  const { record, PerrecordID, isExisted } = await getListByIDNum(person.IDNum);
  if (!isExisted) return setPersonStatusAndNote(originPerson, STATUS.NOT_BUILD);
  const { Chinadr } = await saveTZ(person, { PerrecordID, record });
  const res = await saveZD(person, { record, PerrecordID, Chinadr });
  return { ...originPerson, ...res };
}

// 打开体质辨识页面&保存体质辨识
async function saveTZ(person, { record, PerrecordID } = {}) {
  let pinghezhiAdviceFlag = person.constitutionType.pinghebianshi === "1";
  // 如果倾向是痰湿质，基本是平和质，那么健康指导只选平和质的
  if (
    person.constitutionType.tanshibianshi === "2" &&
    person.constitutionType.pinghebianshi === "2"
  ) {
    pinghezhiAdviceFlag = true;
  }

  const res1 = await jiweiAxios({
    url: "/HR_CHRONIC/AspCode/AnnualExaminationManage/JianKangTiJianGuid/IdentificationOfConstitution.aspx",
    params: {
      PerrecordID,
      Record: record,
    },
    responseType: "arraybuffer",
  });
  // console.log('res2.data',res2.data);
  const CONSITUTION_SCORE = iconv.decode(res1.data, "gb2312");
  const $CONSITUTION_SCORE = cheerio.load(CONSITUTION_SCORE);
  const url1 = $CONSITUTION_SCORE(
    'script[src^="/pyjw/ajaxpro/HR_Chronic_AspCode_AnnualExaminationManage_JianKangTiJianGuid_IdentificationOfConstitution,"]'
  ).attr("src");

  const answer33 = `${person[1]}/${person[2]}/${person[3]}/${person[4]}/${person[5]}/${person[6]}/${person[7]}/${person[8]}/${person[9]}/${person[10]}/${person[11]}/${person[12]}/${person[13]}/${person[14]}/${person[15]}/${person[16]}/${person[17]}/${person[18]}/${person[19]}/${person[20]}/${person[21]}/${person[22]}/${person[23]}/${person[24]}/${person[25]}/${person[26]}/${person[27]}/${person[28]}/${person[29]}/${person[30]}/${person[31]}/${person[32]}/${person[33]}/`;
  const data3 = {
    optiontype: "add",
    idenid: "",
    perrecordid: PerrecordID,
    chkrecordid: "",
    record,
    annu: "",
    anwser33: answer33, // [4/2/1/1/1/1/1/1/3/1/1/1/1/1/1/3/1/1/1/1/1/1/1/1/1/2/2/4/1/1/1/4/1/]
    qixudefen: person.sum.sum1, // 气虚
    qixubianshi: person.constitutionType.qixubianshi,
    qixuzhidao: getAdvice(person.constitutionType.qixubianshi),
    yangxudefen: person.sum.sum2, // 阳虚
    yangxubianshi: person.constitutionType.yangxubianshi,
    yangxuzhidao: getAdvice(person.constitutionType.yangxubianshi),
    yinxudefen: person.sum.sum3, // 阴虚
    yinxubianshi: person.constitutionType.yinxubianshi,
    yinxuzhidao: getAdvice(person.constitutionType.yinxubianshi),
    tanshidefen: person.sum.sum4, // 痰湿
    tanshibianshi: person.constitutionType.tanshibianshi,
    tanshizhidao: getAdvice(person.constitutionType.tanshibianshi),
    shiredefen: person.sum.sum5, // 湿热
    shirebianshi: person.constitutionType.shirebianshi,
    shirezhidao: getAdvice(person.constitutionType.shirebianshi),
    xueyudefen: person.sum.sum6, // 血瘀
    xueyubianshi: person.constitutionType.xueyubianshi,
    xueyuzhidao: getAdvice(person.constitutionType.xueyubianshi),
    qiyudefen: person.sum.sum7, // 气郁
    qiyubianshi: person.constitutionType.qiyubianshi,
    qiyuzhidao: getAdvice(person.constitutionType.qiyubianshi),
    tebingdefen: person.sum.sum8, // 特禀
    tebingbianshi: person.constitutionType.tebingbianshi,
    tebingzhidao: getAdvice(person.constitutionType.tebingbianshi),
    pinghedefen: person.sum.sum9, // 平和
    pinghebianshi: person.constitutionType.pinghebianshi,
    pinghezhidao: getAdvice(pinghezhiAdviceFlag ? "1" : ""),
    tddate: person.tddate,
    tbrenyuan: person.physicalExaminer,
    CHINADR: "",
  };

  function getAdvice(score) {
    const advice = "1/2/3/4/5/6/Ю发放中医药健康教育材料";
    const emptyAdvice = "Ю发放中医药健康教育材料";
    return score === "1" ? advice : emptyAdvice;
  }

  const res2 = await jiweiAxios({
    url: url1.replace("/pyjw", ""),
    headers: {
      "Content-Type": "application/x-www-form-urlencoded",
      "Ajax-method": "InsertIntoIden",
    },
    method: "post",
    data: JSON.stringify(data3),
    responseType: "arraybuffer",
  });
  // 获取体质辨识保存的id
  const Chinadr = iconv.decode(res2.data, "gb2312").replace(/"/g, "");

  return { Chinadr };
}

// 填写指导
async function saveZD(person, { record, PerrecordID, Chinadr }) {
  // 下面两个请求是用来获取体质对应的数字用于指导填写用
  const res1 = await jiweiAxios({
    url: `/Hr_OldHealth/AspCode/OldHealthManage/ZhongYiYaoJianKang.aspx?record=${record}&PerrecordID=${PerrecordID}`,
    responseType: "arraybuffer",
  });
  const RES1 = iconv.decode(res1.data, "gb2312");
  const $RES1 = cheerio.load(RES1);

  const url2 = $RES1(
    'script[src^="/pyjw/ajaxpro/Hr_OldHealth_AspCode_OldHealthManage_ZhongYiYaoJianKang,"]'
  ).attr("src");

  const res2 = await jiweiAxios({
    url: url2,
    headers: {
      "Ajax-method": "GetChinadrByChinadr",
    },
    method: "post",
    data: JSON.stringify({ chinadr: Chinadr }),
    responseType: "arraybuffer",
  });
  const RES2 = iconv.decode(res2.data, "gb2312");
  const oldidenofcon = RES2.replace(/.*(\d{7}).*/, "$1");

  const data3 = {
    Perrecordid: PerrecordID,
    chkrecord: "",
    oldidenofcon,
  };
  const res3 = await jiweiAxios({
    url: url2,
    headers: {
      "Ajax-method": "CheckCh_oldidenofcon",
    },
    method: "post",
    data: JSON.stringify(data3),
    responseType: "arraybuffer",
  });
  const RES3 = iconv.decode(res3.data, "gb2312");
  const OrderId = RES3.replace(/.*"(.*)".*/, "$1");

  // http://xiaogang.3pigcn.com/pyjw/HR_CHRONIC/AspCode/AnnualExaminationManage/JianKangTiJianGuid/OcdHealth.aspx?Chinadr=596517&PerrecordID=68016&Chkrecordid=&OrderId=9&Chkdate=&ChkUsername=
  // 填写指导
  const res4 = await jiweiAxios({
    url: `/HR_CHRONIC/AspCode/AnnualExaminationManage/JianKangTiJianGuid/OcdHealth.aspx?Chinadr=${Chinadr}&PerrecordID=${PerrecordID}&Chkrecordid=&OrderId=${OrderId}`,
    headers: {
      "Ajax-method": "CheckCh_oldidenofcon",
    },
    responseType: "arraybuffer",
  });
  const RES4 = iconv.decode(res4.data, "gb2312");
  const $RES4 = cheerio.load(RES4);

  const data5 = {
    __VIEWSTATE: $RES4("#__VIEWSTATE").val(),
    txtqingzhitiaoshe: $RES4("#txtqingzhitiaoshe").text().trim(),
    txtyinshitiaoyang: $RES4("#txtyinshitiaoyang").text().trim(),
    txtqijutiaoshe: $RES4("#txtqijutiaoshe").text().trim(),
    txtyundongbaojian: $RES4("#txtyundongbaojian").text().trim(),
    txtxueweibaojian: $RES4("#txtxueweibaojian").text().trim(),
    txtDocName: person.physicalExaminer, // 责任医生
    txtbeizhidaoren: $RES4("#txtbeizhidaoren").val(),
    txtzhidaoshijian: person.tddate, // 指导日期
    txtnextsuifang: dayjs(person.tddate, "YYYY-MM-DD")
      .add(1, "year")
      .format("YYYY-MM-DD"), // 随访日期，指导日期加一年
    btnSave: $RES4("#btnSave").val(),
    hdChkrecord: "",
    hdnPerrecordid: $RES4("#hdnPerrecordid").val(),
    hdnOldIden: "",
    hdnOptionType: "",
    hdnIdenID: "",
    hdnRecord: "",
    hdnOcdId: "",
    hdnOrderId: $RES4("#hdnOrderId").val(),
    hdchinadr: $RES4("#hdchinadr").val(),
    __VIEWSTATEGENERATOR: $RES4("#__VIEWSTATEGENERATOR").val(),
    __EVENTVALIDATION: $RES4("#__EVENTVALIDATION").val(),
  };

  const res5 = await jiweiAxios({
    url: `/HR_CHRONIC/AspCode/AnnualExaminationManage/JianKangTiJianGuid/OcdHealth.aspx?Chinadr=${Chinadr}&PerrecordID=${PerrecordID}&Chkrecordid=&OrderId=${OrderId}`,
    method: "post",
    headers: {
      "Content-Type": "application/x-www-form-urlencoded",
    },
    data: commonUtil.jsonToGBKURLString(data5).replace(/%A%/g, "%0D%0A%"),
    responseType: "arraybuffer",
  });

  const RES5 = iconv.decode(res5.data, "gb2312");
  // const $RES8 = cheerio.load(RES8);
  if (RES5.includes("alert('保存成功！')")) {
    return { STATUS: STATUS.FINISH };
  }
  // person.STATUS = STATUS.WRONG;
  return { STATUS: STATUS.WRONG, NOTE: "保存失败，请检查源数据格式" };
}

// 根据身份证查询居民列表
async function getListByIDNum(IDNum) {
  // 打开花名册界面
  const res = await jiweiAxios({
    url: URL.CHINESE_MEDICINE_SEARCH_PAGE,
    responseType: "arraybuffer",
  });
  const SEARCH_PAGE = iconv.decode(res.data, "gb2312");
  const $SEARCH_PAGE = cheerio.load(SEARCH_PAGE);

  const data = {
    ...checkExistParams,
    __VIEWSTATE: $SEARCH_PAGE("#__VIEWSTATE").val(),
    QueryValue: IDNum, // 搜索条件[440xxxx],
    hdnCurrentZoneID: $SEARCH_PAGE("#hdnCurrentZoneID").val(), // [440113012000],
    hdnZoneName: $SEARCH_PAGE("#hdnZoneName").val(), // [大龙街道],
    hdnOrgID: $SEARCH_PAGE("#hdnOrgID").val(), // [4401130049],
    hdnOrgName: $SEARCH_PAGE('script[type="text/javascript"]:last-child')
      .html()
      .replace(/'/g, "")
      .split(",")[1], // [大龙街社区卫生服务中心],
    hdnLoginZoneID: $SEARCH_PAGE("#hdnLoginZoneID").val(), // [440113012000],
    hdnLoginOrgID: $SEARCH_PAGE("#hdnLoginOrgID").val(), // [4401130049],
    hdShow: $SEARCH_PAGE("#hdShow").val(),
    __VIEWSTATEGENERATOR: $SEARCH_PAGE("#__VIEWSTATEGENERATOR").val(),
    __EVENTVALIDATION: $SEARCH_PAGE("#__EVENTVALIDATION").val(),
  };
  const res1 = await jiweiAxios({
    url: URL.CHINESE_MEDICINE_SEARCH_PAGE,
    method: "post",
    headers: {
      "Content-Type": "application/x-www-form-urlencoded",
    },
    data: commonUtil.jsonToGBKURLString(data),
    responseType: "arraybuffer",
  });
  const EXISTED_PAGE = iconv.decode(res1.data, "gb2312");
  const $EXISTED_PAGE = cheerio.load(EXISTED_PAGE);

  const record =
    $EXISTED_PAGE(".AA").attr("onclick") &&
    $EXISTED_PAGE(".AA")
      .attr("onclick")
      .replace(/[^0-9]/gi, "");

  const PerrecordID = $EXISTED_PAGE(".perrecordid").val();
  return { record, PerrecordID, isExisted: !!record };
}

export default main;
